from django.http import HttpResponse
from django.shortcuts import render,redirect
from rest_framework.views import APIView,View
from .models import  User
from rest_framework.response import Response
import jwt
from django_test.settings import SECRET_KEY
import requests
import json
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io
import redis

#定义地址和端口
host = '127.0.0.1'
port = 6379

#建立redis连接
r = redis.Redis(host=host,port=port)

# 定义验证码
class MyCode(View):
    # 定义随机验证颜色
    def get_random_color(self):
        R = random.randrange(255)
        G = random.randrange(255)
        B = random.randrange(255)
        return (R, G, B)

    # 随机验证码
    def get(self, request):
        # 画布
        img_size = (110, 50)
        # 定义颜色类型
        image = Image.new("RGB", img_size, 'white')
        # 画笔
        draw = ImageDraw.Draw(image, 'RGB')
        # 定义随机字符串
        source = '0123456789'
        # 容器，用来接收随机字符串
        code_str = ''
        # 定义字体
        # my_font = ImageFont.truetype(font="c:\\Windows\\Fonts\\STHUPO.TTF", size=15)
        for i in range(4):
            # 获取字体颜色
            text_color = self.get_random_color()
            # 获取字符串
            tmp_num = random.randrange(len(source))
            # 获取字符集
            random_str = source[tmp_num]
            # 添加到容器中
            code_str += random_str
            # 绘制
            draw.text((10 + 30 * i, 20), random_str, text_color)
        # 文件流缓冲区
        buf = io.BytesIO()

        # 将随机码存储到redis中
        r.set('code', code_str)
        # 将验证码存储到session中
        request.session['code'] = code_str
        # print(request.session['code'])
        # 将图片保存到缓冲区
        image.save(buf, 'png')

        return HttpResponse(buf.getvalue(), 'image/png')

# Create your views here.
class LoginView(APIView):
    def post(self,request):
        name = request.POST.get('name')
        password = request.POST.get('password')

        user = User.objects.filter(name=name,password=password).first()

        if user:
            info = {
                'uid':user.id,
                'name':user.name
            }
            token = jwt.encode(info,SECRET_KEY)

            return Response({'msg':'登陆成功','token':token})
        else:
            return Response({'msg':'登陆失败'},status=401)

class TestView(APIView):
    def get(self,request):
        uid = request.COOKIES.get('uid')
        if uid:
            return Response({'msg':'令牌有效'})
        else:
            return Response({'msg':'令牌无效'},status=500)
        # token = request.GET.get('token')
        # # 解析令牌
        # try:
        #     data = jwt.decode(token,SECRET_KEY,algorithms=['HS256'])
        #     print(data)
        #     uid = data.get('uid')
        #     return Response({'msg':'令牌有效'})
        # except Exception as e:
        #     print(e)
        #     return Response({'msg':'令牌无效'},status=500)

    def post(self,request):
        uid = request.COOKIES.get('uid')
        if uid:
            return Response({'msg': '令牌有效'})
        else:
            return Response({'msg': '令牌无效'}, status=500)
        # token = request.POST.get('token')
        # # 解析令牌
        # try:
        #     data = jwt.decode(token,SECRET_KEY,algorithms=['HS256'])
        #     print(data)
        #     uid = data.get('uid')
        #     return Response({'msg':'令牌有效'},status=200)
        # except Exception as e:
        #     print(e)
        #     return Response({'msg':'令牌无效'},status=500)

#新浪微博回调视图
def weibo_back(request):

    #获取code
    code = request.GET.get('code')

    #换取网址
    access_token_url = "https://api.weibo.com/oauth2/access_token"

    #发送请求进行换取
    re_dict = requests.post(
        access_token_url,
        data={
            # app_id应用id
            "client_id": '543875374',
            # app_secret密钥
            "client_secret": "84791387ef015bb4ad3d75425ed30c00",
            # 授权类型code
            "grant_type": "authorization_code",
            # code参数
            "code": code,
            # 回调网址
            "redirect_uri": "http://127.0.0.1:8080/md_admin/weibo"
        }
    )
    print(re_dict.text)

    #强转
    re_dict = re_dict.text
    re_dict = eval(re_dict)

    #判断是否用新浪登陆过
    user = User.objects.filter(username=str(re_dict['uid'])).first()

    sina_id = ''
    user_id = ''

    if user:
        #代表曾经登录过
        sina_id = user.username
        user_id = user.id
    else:
        #自动创建账号
        user = User(username=str(re_dict['uid']),password='',type=0)
        #保存
        user.save()

        #查询用户id
        user = User.objects.filter(username=str(re_dict['uid'])).first()

        sina_id = str(re_dict['uid'])
        user_id = user.id

    #跳转操作
    return redirect('http://localhost:8080?sina_id='+str(sina_id)+"&uid="+str(user_id))

#登录接口
class Login(APIView):

    def get(self,request):

        #接收参数
        username = request.GET.get('username','未收到用户名')
        password = request.GET.get('password','未收到密码')
        code = request.GET.get('code', 'null')

        # 从redis获取验证码
        redis_code = r.get('code')
        redis_code = redis_code.decode('utf-8')
        print(redis_code)

        # 判断验证码是否正确
        if code != redis_code:
            res = {}
            res['code'] = 405
            res['message'] = '验证码输入错误'
            return Response(res)

        # 查询数据
        user = User.objects.filter(username=username, password=password).first()

        if user:
            res = {}
            res['code'] = 200
            res['message'] = '登录成功'
            res['username'] = user.username
            res['uid'] = user.id
            return Response(res)
        else:
            res = {}
            res['code'] = 405
            res['message'] = '用户名或者密码错误'
            return Response(res)

# 注册模块
class Register(APIView):
    def get(self,request):
        # 接收参数
        username = request.GET.get('username','null')
        password = request.GET.get('password','null')

        # 排重
        user = User.objects.filter(username=username).first()

        if user:
            res = {}
            res['code'] = 405
            res['message'] = '该用户名已存在'
            return Response(res)
        # 入库
        user = User(username=username,password=password)
        user.save()

        res = {}
        res['code'] = 200
        res['message'] = '注册成功'

        return Response(res)